<?php
/**
 * 基本数据同步-登陆数据同步
 * @authors xiadx (xiadx@zpdchina.com)
 * @date    2017-03-03 15:26:18
 * @version $Id$
 */

class AsyncwithserverloginController extends Yaf_Controller_Abstract {

    function indexAction()
    {
        // 获取参数 POST方式
    	$params = $this->getRequest()->getPost();
		
    	if (empty($params['user_number'])) {
    		Utility::apiJsonError(10003, '用户名不能为空!');
    	}
    	$user_number = $params['user_number'];

    	if (empty($params['user_department'])) {
    		Utility::apiJsonError(10000, '科室不能为空!');
    	}
    	$user_department = $params['user_department'];
		
    	if (empty($params['user_department_id'])) {
    		Utility::apiJsonError(10004, '科室ID不能为空!');
    	}
    	$user_department_id = $params['user_department_id'];
        // 是否开启压缩 默认开启
        $compression_http_data = $params['compression_http_data'] ? : 'off';
        if (!isset($params['yiyuan_id'])) {
            Utility::apiJsonError(10015, '医院ID不能为空!');
        }
        // 医院ID 默认为0
    	$yiyuan_id = intval($params['yiyuan_id']) ? : 0;
        $session_id = $params['session_id'];

        $async_result['error'] = 200;
        $async_result['msg'] = '';
        $mod_yiuan_user = new YiyuanUserModel;
        //判断是否发送消息
        $sess_id = $mod_yiuan_user->checkOnceLogin($session_id,$user_department,$user_department_id);
    	/*系统参数配置*/
    	$data_mod = new DataBasicParamsConfigModel;
        $field_arr = $data_mod->_field_arr;
        $data = $data_mod->ls();
        $async_result['system_params_config_update_sql'] = Utility::formatToSqlStrExtends($data, 'data_basic_params_config', 'system_params_config_update_sql', $field_arr);

    	/*主菜单配置*/
        $mod_data_mene_config = new DataMenuConfigModel;
    	if (Yaconf::get("config$yiyuan_id.is_permissions_model")) { //根据科室、职责获取终端模块
    		$mokuai_id_arrAll = Utility::array_pluck(
    			DB::select('mokuai_id')
    			->from('data_menu_keshi')
    			->where('yiyuan_id', '=', $yiyuan_id),
    			'mokuai_id');
    		// 获取当前科室绑定的模块id
    		$mokuai_id_arr = Utility::array_pluck(
    			DB::select('mokuai_id')
    			->from('data_menu_keshi')
    			->where('yiyuan_id', '=', $yiyuan_id)
    			->where('keshi_id', '=', $user_department_id),
    			'mokuai_id');

    		// 获取用户职务
    		$user_info = $mod_yiuan_user->departmentPosition($user_number, $user_department);
    		$department_position = $user_info['zpd_department_position'] ?: $user_info['user_department_position'];
    		/*end*/

    		$main_data_menu_config = $mod_data_mene_config->dataMenuForPosition($mokuai_id_arr, $mokuai_id_arrAll, $department_position);
    	} else
    		$main_data_menu_config = $mod_data_mene_config->allDataMenu($yiyuan_id);
        $field_arr = $mod_data_mene_config->_field_arr;
        $async_result['main_data_menu_config'] = Utility::formatToSqlStrExtends($main_data_menu_config, 'data_menu_config', 'main_data_menu_config', $field_arr);
		/*end*/
        
        /*基础参数配置*/
        $params_mod = new DataBasicParamsConfigModel;
        $field_arr = $params_mod->_field_arr;
        $data_basic_params_config = $params_mod->ls();
        $async_result['data_basic_params_config'] = Utility::formatToSqlStrExtends($data_basic_params_config, 'data_basic_params_config', 'data_basic_params_config', $field_arr);
        /*end*/
        
        /*护理评估*/
        $data_hulipinggu_mod = new DataHulipingguBiaodanModel;
        // 返回给终端的可执行sql语句的字段名称数组
        $field_arr = $data_hulipinggu_mod->_field_arr;
        $data_pinggu = $data_hulipinggu_mod->huliPinggu($user_department);
        $async_result['data_hulipinggu_template_update_sql'] = Utility::formatToSqlStrExtends($data_pinggu, 'data_hulipinggu_template', 'data_hulipinggu_template_update_sql', $field_arr);
        /*end*/
        /*体质单列表模板*/
        $data_tizhi_pinggu_mod = new DataTizhiPinggudanTemplateModel;
        $field_arr = $data_tizhi_pinggu_mod->_field_arr;
        $data_tizhi_pinggu = $data_tizhi_pinggu_mod->tizhiPinggu($user_department);
        $async_result['data_tizhi_pinggudan_template_update_sql'] = Utility::formatToSqlStrExtends($data_tizhi_pinggu, 'data_tizhi_pinggudan_template', 'data_tizhi_pinggudan_template_update_sql', $field_arr);
        /*end*/
        
        /*获取体征时间段配置默认显示数据*/
        $data_mod = new DataTizhengShijianPeizhiModel;
        $field_arr = $data_mod->_field_arr;
        $data = $data_mod->ls($user_department);
        $async_result['data_tizheng_shijian_peizhi_update_sql'] = Utility::formatToSqlStrExtends($data, 'data_tizheng_shijian_peizhi', 'data_tizheng_shijian_peizhi_update_sql', $field_arr);
        /*end*/
        /*体征配置*/
        $data_tizheng_template = new DataTizhengTemplateModel;
        $field_arr = $data_tizheng_template->_field_arr;
        $zhuyuan_tizheng_moren = $data_tizheng_template->ls($user_department);
        $async_result['data_tizheng_template_update_sql'] = Utility::formatToSqlStrExtends($zhuyuan_tizheng_moren, 'data_tizheng_template', 'data_tizheng_template_update_sql', $field_arr);
        /*end*/

        
        /*获取所有住院中患者*/
        /*
        $zhuyuan_basic_info_mod = new ZhuyuanBasicInfoModel;
        $field_arr = $zhuyuan_basic_info_mod->_field_arr;
        $zhuyuan_basic_info = $zhuyuan_basic_info_mod->ls($user_department);
        $async_result['zhuyuan_basic_info_update_sql'] = Utility::formatToSqlStrExtends($zhuyuan_basic_info, 'zhuyuan_basic_info', 'zhuyuan_basic_info_update_sql', $field_arr);
        */
        /*end*/

        /*获取医院床位信息*/
        $yiyuan_chuangwei_mod = new YiyuanBingchuangModel;
        $field_arr = $yiyuan_chuangwei_mod->_field_arr;
        $yiyuan_chuangwei = $yiyuan_chuangwei_mod->ls($user_department);
        $async_result['bingchuang_update_sql'] = Utility::formatToSqlStrExtends($yiyuan_chuangwei, 'yiyuan_bingchuanghao', 'bingchuang_update_sql', $field_arr);
        /*end*/
        /*获取巡查记录信息*/
        $data_xuncha_jilu_mod = new DataXunchajiluItemModel;
        $field_arr = $data_xuncha_jilu_mod->_field_arr;
        $data_xunchajilu_item = $data_xuncha_jilu_mod->ls($user_department);
        $async_result['xunchajilu_item'] = Utility::formatToSqlStrExtends($data_xunchajilu_item, 'data_xuncha_item', 'xunchajilu_item', $field_arr);
        /*end*/

        
        /*获取情景模式*/
        $data_input_frequency_mod = new DataInputFrequencyModel;
        $field_arr = $data_input_frequency_mod->_field_arr;
        $data_input_frequency = $data_input_frequency_mod->ls($user_department);
        $async_result['qingjing_update_sql'] = Utility::formatToSqlStrExtends($data_input_frequency, 'data_input_frequency', 'qingjing_update_sql', $field_arr);
        /*end*/
        /*add by xiadx @20170317 */
        $async_result["qingjing_update_sql"] = '';
        foreach ($data_input_frequency as $key => $one) {
            if($key == 0)
            {
                $async_result["qingjing_update_sql"] .= "REPLACE INTO data_input_frequency (id,type,item_name,item_code,daily_need,hulijibie) SELECT  '".$one["id"]."','".$one["type"]."','".$one["item_name"]."','".$one["item_code"]."','".$one["daily_need"]."','".$one["hulijibie"]."'";
            }
            else
            {
                $async_result["qingjing_update_sql"] .= " union all SELECT '".$one["id"]."','".$one["type"]."','".$one["item_name"]."','".$one["item_code"]."','".$one["daily_need"]."','".$one["hulijibie"]."'";
            }
        }
        /*end*/

        /*获取住院情景模式*/
        $data_mod = new ZhuyuanBlockTemplateModel;
        $field_arr = $data_mod->_field_arr;
        $data = $data_mod->ls($user_department);
        $async_result['zhuyuan_block_template_update_sql'] = Utility::formatToSqlStrExtends($data, 'zhuyuan_block_template', 'zhuyuan_block_template_update_sql', $field_arr);
        $async_result["zhuyuan_block_template_update_sql"] = '';
        foreach ($data as $key => $one) {
        	if ($key == 0) {
        		$async_result["zhuyuan_block_template_update_sql"] .= "REPLACE INTO zhuyuan_block_template (id,type,name,content,keshi,template_name) SELECT  '".$one["id"]."','".$one["type"]."','".$one["name"]."','".$one["content"]."','".$one["keshi"]."','".$one["template_name"]."'";
        	} else {
        		$async_result["zhuyuan_block_template_update_sql"] .= " union all SELECT '".$one["id"]."','".$one["type"]."','".$one["name"]."','".$one["content"]."','".$one["keshi"]."','".$one["template_name"]."'";
        	}
        }
        
        /*获取护理统计item*/
        $data_mod = new DataHulitongjiItemModel;
        $field_arr = $data_mod->_field_arr;
        $data = $data_mod->ls();
        $async_result['hulitongji_item_update_sql'] = Utility::formatToSqlStrExtends($data, 'data_hulitongji_item', 'hulitongji_item_update_sql', $field_arr);
        /*end*/
        /*获取护理记录单项列表模板*/
        $data_temp_mod = new DataHulijiluTemplateModel;
        $field_arr = $data_temp_mod->_field_arr;
        $data = $data_temp_mod->ls($user_department);
        $ids = Utility::array_pluck($data, 'id');
        $async_result['data_hulijilu_template_update_sql'] = Utility::formatToSqlStrExtends($data, 'data_hulijilu_template', 'data_hulijilu_template_update_sql', $field_arr);
        /*end*/

        /*获取护理记录单项子项列表模板*/
        $data_mod = new DataHulijiluTemplateItemModel;
        $data_dictionary_mod = new DataDictionaryModel;
        $data = $data_mod->ls($ids);
        $sub_name_arrs = Utility::array_pluck($data, 'sub_name', 'id');
        $sub_status_arrs = Utility::array_pluck($data, 'sub_status', 'id');
        $huli_temp_id_arrs = Utility::array_pluck($data, 'huli_temp_id', 'id');
        $res = $data_dictionary_mod->ls($sub_name_arrs);
        // 如果存在状态的话,增加护理记录模板数据的排序返回
        $zhuangtai = $data_dictionary_mod->ls($sub_status_arrs);
        $biaodan_name_arrs = $data_temp_mod->getXiangmuNameBySubId($huli_temp_id_arrs, 'biaodan_name');
        $xiangmu_name_arrs = $data_temp_mod->getXiangmuNameBySubId($huli_temp_id_arrs, 'xiangmu_name');
        $num = 1;
        foreach ($data as $item) {
            if (isset($res[$item['id']])) {
                $ztm = 0;//当该值为0且其他值1时,
                foreach ($res[$item['id']] as $sub_item) {
                    if (isset($zhuangtai[$item['id']])) {
                        foreach ($zhuangtai[$item['id']] as $i) {
                            // $count++;
                            $temp['id'] = $num++;
                            $temp['leibie'] = $sub_item["dictdata_name"];
                            $temp['fangshi'] = $i["dictdata_name"];
                            $temp['max'] = $item['max'];
                            $temp['min'] = $item['min'];
                            $temp['danwei'] = $item['danwei'];
                            $temp['edit_number'] = 1;
                            $temp['leibie_miaoshu'] = $xiangmu_name_arrs[$item['id']];
                            $temp['ztm'] = ($ztm == 0 && ($sub_item['isfixed'] == 1 || $i['isfixed'] == 1)) ? 1 : 0;
                            $temp['keshi'] = $item['keshi'];
                            $temp['keyboardname'] = $item['keyboardname'];
                            $temp['xiangmu_value'] = '';
                            $temp['default_value'] = '';
                            /*add by xiadx @20160711 for 修复不同表单名称下面的同名护理项目的bug*/
                            $temp['biaodan_name'] = $biaodan_name_arrs[$item['id']];
                            /*end*/
                            $new_arr[] = $temp;
                            $ztm++;
                        }
                    } else {
                        $temp['id'] = $num++;
                        $temp['leibie'] = $sub_item["dictdata_name"];
                        $temp['fangshi'] = '';
                        $temp['max'] = $item['max'];
                        $temp['min'] = $item['min'];
                        $temp['danwei'] = $item['danwei'];
                        $temp['edit_number'] = 1;
                        $temp['leibie_miaoshu'] = $xiangmu_name_arrs[$item['id']];
                        $temp['ztm'] = $sub_item['isfixed'];
                        $temp['keshi'] = $item['keshi'];
                        $temp['keyboardname'] = $item['keyboardname'];
                        $temp['xiangmu_value'] = '';
                        $temp['default_value'] = '';
                        /*add by xiadx @20160711 for 修复不同表单名称下面的同名护理项目的bug*/
                        $temp['biaodan_name'] = $biaodan_name_arrs[$item['id']];
                        /*end*/
                        $new_arr[] = $temp;
                    }
                }
            }
        }

        $per_number = 100;
        foreach ($new_arr as $key => $sub_item) {
            $j = intval($key/$per_number);
            //每组第几个
            $arr_zer = $key%$per_number;
            if($arr_zer == 0){
                $async_result["data_hulijilu_guanli_template_update_sql"][$j] .= "REPLACE INTO data_hulijilu_guanli_template(jilu_id,leibie,fangshi,max,min,danwei,edit_number,leibie_miaoshu,ztm,keshi,keyboardname,xiangmu_value,default_value,biaodan_name) SELECT  '".$sub_item["id"]."','".$sub_item["leibie"]."','".$sub_item["fangshi"]."','".$sub_item["max"]."','".$sub_item["min"]."','".$sub_item["danwei"]."','".$sub_item["edit_number"]."','".$sub_item["leibie_miaoshu"]."','".$sub_item["ztm"]."','".$sub_item["keshi"]."','".$sub_item["keyboardname"]."','','','" . $sub_item['biaodan_name'] . "'";
            } else {
                $async_result["data_hulijilu_guanli_template_update_sql"][$j] .= " union all SELECT '".$sub_item["id"]."','".$sub_item["leibie"]."','".$sub_item["fangshi"]."','".$sub_item["max"]."','".$sub_item["min"]."','".$sub_item["danwei"]."','".$sub_item["edit_number"]."','".$sub_item["leibie_miaoshu"]."','".$sub_item["ztm"]."','".$sub_item["keshi"]."','".$sub_item["keyboardname"]."','','','" . $sub_item['biaodan_name'] . "'";
            }
        }
        /*end*/
        /*新增多编辑升级版数据返回*/
        $data_mod_huli_extend = new DataHulijiluTemplateSubExtendModel;
        $data = $data_mod_huli_extend->ls();
        $async_result["data_hulijilu_multiedit_template_update_sql"] = $data_temp_mod->lsSubItem($user_department, $data, $per_number);
        /*end*/
        /*获取yiyuan_user数据*/
        $mod_yiuan_user = new YiyuanUserModel;
        $user_list = $mod_yiuan_user->ls($user_department);
        $tiaoshu = 200;
        $number = ceil(count($user_list)/$tiaoshu);
        for($i = 0; $i < $number; $i++)
        {
            $value = $i * $tiaoshu;
            $content = array_slice($user_list,$value,$tiaoshu);
            foreach($content as $key => $one)
            {
                // TODO
                $one["scan_user_number"] = substr(md5("GP".$one["user_number"]),8,16);
                $one["user_department"] = $user_department;

                if($key == 0)
                {
                    $async_result["yiyuan_user_update_sql"][$i] .= "REPLACE INTO yiyuan_user (id,user_number,scan_user_number,user_name,user_department,login_password) SELECT  '".$one["id"]."','".$one["user_number"]."','".$one["scan_user_number"]."','".$one["user_name"]."','".$one["user_department"]."','".$one["login_password"]."'";
                }
                else
                {
                    $async_result["yiyuan_user_update_sql"][$i] .= " union all SELECT '".$one["id"]."','".$one["user_number"]."','".$one["scan_user_number"]."','".$one["user_name"]."','".$one["user_department"]."','".$one["login_password"]."'";
                }
            }
        }
        /*end*/
        /*保存session*/
        if(!$sess_id)
        {
            $mod_yiuan_user->_after_asyncWithServerLogin($user_department,$user_department_id);
        }
        Utility::apiJsonResultExtends($async_result);
    }
}
